<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品列表 - 跨境电商竞品分析系统</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
    <!-- 传递服务器设置到前端 JavaScript -->
    <script>
        window.defaultProductImage = "{{ default_product_image }}";
        window.fallbackImageUrl = "{{ fallback_image_url }}";
    </script>
    <style>
        :root {
            --primary-color: #5e72e4;
            --primary-dark: #4a5fd0;
            --secondary-color: #ff7eb3;
            --accent-color: #11cdef;
            --light-color: #f8f9fe;
            --dark-color: #32325d;
            --success-color: #2dcb73;
            --warning-color: #fb6340;
            --danger-color: #f5365c;
            --info-color: #6a9ef7;
            --pink-gradient: linear-gradient(120deg, #f093fb 0%, #f5576c 100%);
            --blue-gradient: linear-gradient(135deg, #5e72e4 0%, #825ee4 100%);
            --green-gradient: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
        }
        body {
            background-color: #f8f9fe;
            font-family: 'Nunito', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: var(--dark-color);
        }
        .page-header {
            background: var(--blue-gradient);
            color: white;
            padding: 3rem 0;
            position: relative;
            overflow: hidden;
            margin-bottom: 3rem;
        }
        .page-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: url('https://img.freepik.com/free-vector/network-mesh-wire-digital-technology-background_1017-27428.jpg');
            background-size: cover;
            background-position: center;
            opacity: 0.1;
            z-index: 0;
        }
        .page-header-content {
            position: relative;
            z-index: 1;
        }
        .circle {
            position: absolute;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.05);
        }
        .circle-1 {
            width: 200px;
            height: 200px;
            top: -50px;
            right: -30px;
        }
        .circle-2 {
            width: 100px;
            height: 100px;
            bottom: -20px;
            left: 10%;
        }
        .product-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 25px rgba(50, 50, 93, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
            transition: all 0.3s ease;
            height: 100%;
            display: flex;
            flex-direction: column;
            border: 1px solid rgba(0,0,0,0.05);
        }
        .product-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 15px 35px rgba(50, 50, 93, 0.15), 0 10px 25px rgba(0, 0, 0, 0.1);
        }
        .product-image {
            height: 220px;
            overflow: hidden;
            position: relative;
        }
        .product-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s ease;
        }
        .product-card:hover .product-image img {
            transform: scale(1.1);
        }
        .product-content {
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }
        .product-status {
            position: absolute;
            top: 15px;
            right: 15px;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.8rem;
            z-index: 2;
            box-shadow: 0 5px 10px rgba(0,0,0,0.1);
        }
        .status-completed {
            background: var(--success-color);
            color: white;
        }
        .status-pending {
            background: var(--warning-color);
            color: white;
        }
        .product-date {
            font-size: 0.85rem;
            color: #8898aa;
            margin-bottom: 0.5rem;
        }
        .product-title {
            font-weight: 700;
            font-size: 1.2rem;
            margin-bottom: 0.8rem;
            color: var(--dark-color);
        }
        .product-description {
            color: #8898aa;
            font-size: 0.95rem;
            margin-bottom: 1.2rem;
            flex-grow: 1;
            line-height: 1.6;
        }
        .product-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #adb5bd;
            font-size: 0.9rem;
        }
        .product-meta span {
            display: flex;
            align-items: center;
        }
        .product-meta i {
            margin-right: 5px;
            color: var(--primary-color);
        }
        .empty-state {
            background: white;
            border-radius: 15px;
            padding: 3rem;
            text-align: center;
            box-shadow: 0 10px 25px rgba(50, 50, 93, 0.1), 0 5px 15px rgba(0, 0, 0, 0.07);
        }
        .empty-icon {
            width: 120px;
            height: 120px;
            margin: 0 auto 2rem;
            background: var(--light-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--info-color);
            font-size: 3rem;
        }
        .btn-create-product {
            background: var(--pink-gradient);
            border: none;
            font-weight: 700;
            padding: 0.8rem 1.5rem;
            border-radius: 50px;
            box-shadow: 0 7px 14px rgba(245, 87, 108, 0.3);
            letter-spacing: 0.3px;
            transition: all 0.3s ease;
        }
        .btn-create-product:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 20px rgba(245, 87, 108, 0.4);
        }
        .btn-outline-light {
            border-radius: 50px;
            font-weight: 600;
            padding: 0.6rem 1.2rem;
        }
        .navbar-brand {
            font-weight: 800;
            color: white;
            font-size: 1.4rem;
        }
        /* 对比模式相关样式 */
        .product-card.selected {
            border: 2px solid var(--primary-color);
            box-shadow: 0 15px 35px rgba(94, 114, 228, 0.2), 0 10px 25px rgba(0, 0, 0, 0.1);
            transform: translateY(-5px);
        }
        
        .product-card {
            cursor: pointer;
        }
        .product-checkbox {
            position: absolute;
            top: 15px;
            left: 15px;
            z-index: 5;
            background: rgba(255,255,255,0.9);
            border-radius: 50%;
            width: 32px;
            height: 32px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background: var(--dark-color);">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fas fa-globe-asia me-2"></i>竞品分析系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="/products">产品列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/create-product">创建分析</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/compare-products">产品对比</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/wordcloud">
                            <i class="fas fa-cloud me-1"></i>词云分析
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/chat">
                            <i class="fas fa-comment-dots me-1"></i>AI 助手
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 页面头部 -->
    <div class="page-header">
        <div class="circle circle-1"></div>
        <div class="circle circle-2"></div>
        <div class="container page-header-content">
            <div class="row align-items-center">
                <div class="col-lg-8">
                    <h1 class="fw-bold mb-3">我的产品列表</h1>
                    <p class="lead mb-4">查看和管理您的所有产品分析项目，快速掌握市场动态</p>
                </div>
                <div class="col-lg-4 text-end">
                    <a href="/create-product" class="btn btn-create-product me-2">
                        <i class="fas fa-plus-circle me-2"></i>创建新分析
                    </a>
                    <a href="/compare-products" class="btn btn-primary">
                        <i class="fas fa-exchange-alt me-2"></i>产品对比
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 主要内容 -->
    <div class="container mb-5">
        <!-- 筛选器 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="input-group">
                    <span class="input-group-text bg-white border-end-0">
                        <i class="fas fa-search text-muted"></i>
                    </span>
                    <input type="text" id="searchInput" class="form-control border-start-0" placeholder="搜索产品名称...">
                </div>
            </div>
            <div class="col-md-6 text-md-end mt-3 mt-md-0">
                <div class="btn-group me-2" role="group">
                    <button type="button" class="btn btn-outline-primary active filter-btn" data-filter="all">全部</button>
                    <button type="button" class="btn btn-outline-primary filter-btn" data-filter="completed">已完成</button>
                    <button type="button" class="btn btn-outline-primary filter-btn" data-filter="pending">进行中</button>
                </div>
                <button id="compareBtn" class="btn btn-primary" disabled>
                    <i class="fas fa-exchange-alt me-1"></i> 对比选中产品
                </button>
            </div>
        </div>

        <!-- 对比模式提示 -->
        <div id="compareMode" class="alert alert-info d-flex align-items-center mb-4" style="display: none !important;">
            <div class="me-3">
                <i class="fas fa-info-circle fs-4"></i>
            </div>
            <div>
                <strong>产品对比模式:</strong> 请选择2-4个已完成分析的产品进行对比分析。
            </div>
            <div class="ms-auto">
                <button id="cancelCompare" class="btn btn-outline-secondary btn-sm">
                    <i class="fas fa-times me-1"></i> 取消
                </button>
            </div>
        </div>

        <!-- 产品列表 -->
        <div class="row" id="productsContainer">
            <!-- 产品卡片将通过API动态加载 -->
        </div>

        <!-- 空状态提示 -->
        <div id="emptyState" style="display: none;">
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="fas fa-box-open"></i>
                </div>
                <h3 class="mb-3">暂无产品分析</h3>
                <p class="text-muted mb-4">您还没有创建任何产品分析项目。创建一个新的分析，开始探索竞品特性！</p>
                <a href="/create-product" class="btn btn-create-product">
                    <i class="fas fa-plus-circle me-2"></i>创建第一个分析
                </a>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 产品对比功能变量
            let compareMode = false;
            let selectedProducts = [];
            const MAX_COMPARE_PRODUCTS = 4;
            
            // 切换对比模式
            function toggleCompareMode() {
                compareMode = !compareMode;
                document.getElementById('compareMode').style.display = compareMode ? 'flex' : 'none';
                
                // 重置所有选择
                selectedProducts = [];
                updateCompareButton();
                
                // 显示/隐藏所有勾选框
                const checkboxes = document.querySelectorAll('.product-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.style.display = compareMode ? 'flex' : 'none';
                });
                
                // 重新渲染产品以更新选择状态
                renderProducts(allProducts.filter(p => {
                    const status = p.has_analysis ? 'completed' : 'pending';
                    const activeFilter = document.querySelector('.filter-btn.active').getAttribute('data-filter');
                    const searchValue = document.getElementById('searchInput').value.toLowerCase();
                    const matchesSearch = p.name.toLowerCase().includes(searchValue);
                    const matchesFilter = activeFilter === 'all' || status === activeFilter;
                    return matchesSearch && matchesFilter;
                }));
            }
            
            // 更新对比按钮状态
            function updateCompareButton() {
                const compareBtn = document.getElementById('compareBtn');
                compareBtn.disabled = selectedProducts.length < 2;
                compareBtn.innerHTML = `<i class="fas fa-exchange-alt me-1"></i> 对比选中产品 (${selectedProducts.length})`;
                
                // 如果有足够的选中产品，添加启用事件监听器
                if (selectedProducts.length >= 2) {
                    compareBtn.onclick = startComparison;
                } else {
                    compareBtn.onclick = null;
                }
            }
            
            // 获取系统配置的默认图片和备用图片URL
            // 如果服务器没有提供则使用前端默认值
            const defaultProductImage = window.defaultProductImage || "Screenshot_20250416_121955.jpg";
            const fallbackImageUrl = window.fallbackImageUrl || "https://img.freepik.com/free-vector/image-upload-concept-illustration_114360-798.jpg";
            
            // 开始产品对比
            function startComparison() {
                window.location.href = '/compare-products?products=' + selectedProducts.join(',');
            }
            
            // 处理产品选择
            function handleProductSelect(productId, hasAnalysis) {
                if (!compareMode) return;
                
                // 只能选择已完成分析的产品
                if (!hasAnalysis) {
                    alert('只能选择已完成分析的产品进行对比');
                    return;
                }
                
                const index = selectedProducts.indexOf(productId);
                if (index > -1) {
                    // 取消选择
                    selectedProducts.splice(index, 1);
                } else {
                    // 添加选择
                    if (selectedProducts.length >= MAX_COMPARE_PRODUCTS) {
                        alert(`最多可以选择 ${MAX_COMPARE_PRODUCTS} 个产品进行对比`);
                        return;
                    }
                    selectedProducts.push(productId);
                }
                
                // 更新UI显示
                updateProductSelectionUI();
                updateCompareButton();
            }
            
            // 更新产品选择UI
            function updateProductSelectionUI() {
                const cards = document.querySelectorAll('.product-card');
                cards.forEach(card => {
                    const productId = card.getAttribute('data-product-id');
                    const isSelected = selectedProducts.includes(productId);
                    
                    // 更新卡片样式
                    if (isSelected) {
                        card.classList.add('selected');
                    } else {
                        card.classList.remove('selected');
                    }
                    
                    // 更新勾选图标
                    const checkIcon = card.querySelector('.product-checkbox i');
                    if (checkIcon) {
                        checkIcon.className = isSelected ? 'fas fa-check-circle text-primary' : 'fas fa-circle text-muted';
                    }
                    
                    // 更新选择按钮文本
                    const selectBtn = card.querySelector('.product-meta button');
                    if (selectBtn) {
                        selectBtn.className = isSelected ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-outline-primary';
                        selectBtn.textContent = isSelected ? '已选择' : '选择对比';
                    }
                });
            }
            
            // 设置对比模式相关事件监听
            document.getElementById('compareBtn').addEventListener('click', function() {
                if (selectedProducts.length >= 2) {
                    startComparison();
                } else if (!compareMode) {
                    toggleCompareMode();
                }
            });
            document.getElementById('cancelCompare').addEventListener('click', toggleCompareMode);
            
            // 产品搜索功能
            const searchInput = document.getElementById('searchInput');
            searchInput.addEventListener('keyup', function() {
                filterProducts();
            });
            
            // 筛选按钮功能
            const filterButtons = document.querySelectorAll('.filter-btn');
            filterButtons.forEach(button => {
                button.addEventListener('click', function() {
                    filterButtons.forEach(btn => btn.classList.remove('active'));
                    this.classList.add('active');
                    filterProducts();
                });
            });
            
            // 存储产品数据
            let allProducts = [];
            
            // 格式化日期函数
            function formatDate(timestamp) {
                const date = new Date(timestamp * 1000); // 转换为毫秒
                return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式
            }
            
            // 从API加载产品数据
            function loadProducts() {
                // 显示加载状态
                const productsContainer = document.getElementById('productsContainer');
                productsContainer.innerHTML = '<div class="col-12 text-center py-5"><div class="spinner-border text-primary" role="status"></div><p class="mt-3">加载产品中...</p></div>';
                
                fetch('/api/products')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('获取产品列表失败');
                        }
                        return response.json();
                    })
                    .then(data => {
                        allProducts = data;
                        renderProducts(allProducts);
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        productsContainer.innerHTML = `<div class="col-12 text-center py-5"><div class="alert alert-danger" role="alert">加载失败: ${error.message}</div></div>`;
                    });
            }
            
            // 渲染产品卡片
            function renderProducts(products) {
                const productsContainer = document.getElementById('productsContainer');
                const emptyState = document.getElementById('emptyState');
                
                if (!products || products.length === 0) {
                    productsContainer.style.display = 'none';
                    emptyState.style.display = 'block';
                    return;
                }
                
                productsContainer.style.display = 'flex';
                emptyState.style.display = 'none';
                
                productsContainer.innerHTML = '';
                
                products.forEach(product => {
                    const status = product.has_analysis ? 'completed' : 'pending';
                    const statusText = product.has_analysis ? '已完成' : '进行中';
                    const statusClass = product.has_analysis ? 'status-completed' : 'status-pending';
                    
                    // 为产品封面图获取图片路径
                    const imagePath = product.image_count > 0 
                        ? `/static/uploads/products/${product.id}/${product.cover_image || defaultProductImage}`
                        : fallbackImageUrl;
                    
                    // 检查是否被选中用于对比
                    const isSelected = selectedProducts.includes(product.id);
                    
                    const productCard = document.createElement('div');
                    productCard.className = 'col-md-4 mb-4 product-item';
                    productCard.setAttribute('data-status', status);
                    
                    const cardHTML = `
                        <div class="product-card ${isSelected ? 'selected' : ''}" data-product-id="${product.id}">
                            <div class="product-checkbox" style="display: ${compareMode ? 'flex' : 'none'};">
                                <i class="fas ${isSelected ? 'fa-check-circle text-primary' : 'fa-circle text-muted'}" style="font-size: 24px;"></i>
                            </div>
                            <div class="product-image">
                                <span class="product-status ${statusClass}">${statusText}</span>
                                <img src="${imagePath}" alt="${product.name}" 
                                     onerror="this.src='${fallbackImageUrl}'">
                            </div>
                            <div class="product-content">
                                <div class="product-date">
                                    <i class="far fa-calendar-alt me-1"></i> ${formatDate(product.created_time)}
                                </div>
                                <h5 class="product-title">${product.name}</h5>
                                <p class="product-description">
                                    ${product.has_analysis 
                                        ? '已完成分析，点击查看详细结果。'
                                        : `已上传${product.image_count}张图片，等待分析处理。`}
                                </p>
                                <div class="product-meta">
                                    <span><i class="fas fa-image"></i> ${product.image_count}张图片</span>
                                    ${compareMode ? 
                                      `<button class="btn btn-sm ${isSelected ? 'btn-primary' : 'btn-outline-primary'}">${isSelected ? '已选择' : '选择对比'}</button>` :
                                      `<a href="/products/${product.id}" class="text-primary fw-bold text-decoration-none">查看详情</a>`
                                    }
                                </div>
                            </div>
                        </div>
                    `;
                    
                    productCard.innerHTML = cardHTML;
                    productsContainer.appendChild(productCard);
                    
                    // 添加卡片点击事件
                    const card = productCard.querySelector('.product-card');
                    card.addEventListener('click', function(e) {
                        if (compareMode) {
                            handleProductSelect(product.id, product.has_analysis);
                        } else {
                            // 如果不是对比模式，点击卡片跳转到产品详情
                            if (!e.target.closest('button')) {
                                window.location.href = `/products/${product.id}`;
                            }
                        }
                    });
                    
                    // 为选择按钮单独添加事件
                    const selectBtn = card.querySelector('.product-meta button');
                    if (selectBtn) {
                        selectBtn.addEventListener('click', function(e) {
                            e.stopPropagation(); // 阻止事件冒泡
                            handleProductSelect(product.id, product.has_analysis);
                        });
                    }
                });
            }
            
            // 筛选产品的函数
            function filterProducts() {
                const searchValue = searchInput.value.toLowerCase();
                const activeFilter = document.querySelector('.filter-btn.active').getAttribute('data-filter');
                
                const filteredProducts = allProducts.filter(product => {
                    const status = product.has_analysis ? 'completed' : 'pending';
                    const matchesSearch = product.name.toLowerCase().includes(searchValue);
                    const matchesFilter = activeFilter === 'all' || status === activeFilter;
                    
                    return matchesSearch && matchesFilter;
                });
                
                renderProducts(filteredProducts);
            }
            
            // 初始加载产品
            loadProducts();
        });
    </script>
</body>
</html> 